package cn.gdcp.recyclerview;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Toast;

import java.util.ArrayList;

/**
 * Created by yls on 2018/10/22.
 */

public class StuAdapter extends RecyclerView.Adapter<StuViewHolder> {
    private Context context;
    private ArrayList<Student> studentArrayList;
    private IOnitemClick listener;
    private IOnitemClick ionitemclick = new IOnitemClick() {
        @Override
        public void IOnitemClick(int i, View v) {
            switch (v.getId()) {
                case R.id.iv_del:
                    Toast.makeText(context, "删除：" +
                            i, Toast.LENGTH_SHORT).show();
                    studentArrayList.remove(i);
                    notifyDataSetChanged();
                    break;
            }
        }
    };
    public void setItemClick(IOnitemClick listener) {
        this.ionitemclick = listener;
    }
    public StuAdapter(Context context, ArrayList<Student> studentArrayList) {
        this.context = context;
        this.studentArrayList = studentArrayList;
    }

    @Override
    public StuViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(context).inflate(R.layout.list_item,
                viewGroup, false);
        //StuViewHolder viewHolder = new StuViewHolder(view);
        StuViewHolder viewHolder = new StuViewHolder(view, listener);
        viewHolder.listener = ionitemclick;
        return viewHolder;
    }

    public void setItemOnClick(IOnitemClick listener) {
        this.listener = listener;
    }
    public void changeData(ArrayList<Student> studentArrayList){
        this.studentArrayList = studentArrayList;
        notifyDataSetChanged();
    }
    @Override
    public void onBindViewHolder(StuViewHolder holder, final int i) {
        final Student s = studentArrayList.get(i);
        holder.headView.setImageResource(s.getImgId());
        holder.nameView.setText(s.getName());
        holder.ageView.setText(String.valueOf(s.getAge()));

        holder.ivDel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                removeData(i);
            }
        });
    }

    public void removeData(int position){
        studentArrayList.remove(position);
        notifyItemRemoved(position);
        notifyDataSetChanged();
    }

    @Override
    public int getItemCount() {
        return studentArrayList.size();
    }
}